package com.stylefeng.guns.core.base.warpper;


import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器查询结果的包装类基类
 *
 * @author fengshuonan
 * @date 2017年2月13日 下午10:49:36
 */
public abstract class BaseControllerWarpper {

    public Object obj = null;

    public BaseControllerWarpper(Object obj) {
        this.obj = obj;
    }

    @SuppressWarnings("unchecked")
    public Object warp() {
        if (this.obj instanceof List) {
            List<Map<String, Object>> list = (List<Map<String, Object>>) this.obj;
            List<Map<String, Object>> newList = new ArrayList<>();
            for(int i=0;i<list.size();i++){
                Map<String, Object> map = beanToMap(list.get(i));
                warpTheMap(map);
                newList.add(map);
            }
            return newList;
        } else if (this.obj instanceof Map) {
            Map<String, Object> map = beanToMap(this.obj);
            warpTheMap(map);
            return map;
        } else {
            Map<String, Object> map = beanToMap(this.obj);
            warpTheMap(map);
            return map;
        }
    }

    /**
     * 将javabean转为map
     * @param bean
     */
    private Map<String,Object> beanToMap(Object bean){
        if(bean instanceof Map){
            return (Map<String,Object>)bean;
        }
        Map<String,Object> mapResult = new HashMap<>();
        try {
            Map<String, String> map = BeanUtils.describe(bean);
            for (String key : map.keySet()) {
                mapResult.put(key,map.get(key));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return mapResult;
    }

    protected abstract void warpTheMap(Map<String, Object> map) ;
}
